package com.xuanxu.framework.knife4j.config;

import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.ApiSelectorBuilder;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

import java.util.List;

/**
 * @author XuanXu
 * @version 1.0
 * @date 2024-06-16 18:26
 */
@AutoConfiguration()
@EnableConfigurationProperties(Knife4jProperties.class)
@EnableSwagger2WebMvc
@RequiredArgsConstructor
public class Knife4jConfiguration {

    private final Knife4jProperties knife4jProperties;

    /**
     * admin 接口文档
     */
    @Bean
    public Docket adminConfig() {
        ApiSelectorBuilder apiSelectorBuilder = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(knife4jProperties.getAdminEnable())
                .groupName(knife4jProperties.getAdminGroupName())
                .select()
                .paths(PathSelectors.any());

        setApis(apiSelectorBuilder, knife4jProperties.getAdminBasePackage());
        return apiSelectorBuilder.build();
    }

    /**
     * app 接口文档
     */
    @Bean
    public Docket appConfig() {
        ApiSelectorBuilder apiSelectorBuilder = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(knife4jProperties.getAppEnable())
                .groupName(knife4jProperties.getAppGroupName())
                .select()
                .paths(PathSelectors.any());

        setApis(apiSelectorBuilder, knife4jProperties.getAppBasePackage());
        return apiSelectorBuilder.build();
    }

    /**
     * 构建接口文档扫描路径
     */
    private void setApis(ApiSelectorBuilder apiSelectorBuilder, List<String> basePackageUrls) {

        if (basePackageUrls != null && !basePackageUrls.isEmpty()) {
            basePackageUrls.forEach(basePackageUrl ->
                    apiSelectorBuilder.apis(RequestHandlerSelectors.basePackage(basePackageUrl)));
        }
    }

    /**
     * 构建接口文档基本属性
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(knife4jProperties.getTitle())
                .description(knife4jProperties.getDescription())
                .version(knife4jProperties.getVersion())
                .build();
    }
}
